package com.token.iot.bratterycharging.gateway.server;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.outstanding.framework.base.OutstandingService;
import com.outstanding.framework.base.SpringContextHolder;
import com.outstanding.framework.core.Logger;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.core.TransactionContext;
import com.outstanding.framework.log.LoggerFactory;
import com.outstanding.framework.utils.NetUtils;
import com.token.iot.bratterycharging.gateway.ChannelHandlerContextManager;
import com.token.iot.bratterycharging.gateway.Code;
import com.token.iot.bratterycharging.gateway.CodeType;
import com.token.iot.bratterycharging.gateway.Sender;
import com.token.iot.bratterycharging.gateway.api.Constant;
import com.token.iot.bratterycharging.gateway.dao.CodeHistoryDAO;
import com.token.iot.bratterycharging.gateway.utils.ChannelHandlerContextUtil;





import io.netty.channel.ChannelHandlerContext;
/**
 * 一般都是dubbo调用，所以已经有了Context上下文等
 * @author chenzhixuan
 *
 */
@Service
public class SenderService extends OutstandingService {

	@Autowired
	private CodeHistoryDAO dao;
	
	private static Logger loger = LoggerFactory.getLogger(SenderService.class);

	private static ChannelHandlerContextManager manager = new ChannelHandlerContextManager();

	public Object process(Sender sender,String imei, Map<String, String> params) throws PendingException{
		try {
			Object obj = sender.send(imei, params);
			return obj;
		}finally {	
			try {
				Code code = new Code();
				if(imei != null) {
					//查找对应的HandlerContext
					try {
						ChannelHandlerContext context = manager.getChannelHandlerContextByImei(imei);
						String ip = ChannelHandlerContextUtil.getIP(context);
						code.setIp(ip);
					}catch(PendingException e) {
						
					}
				}
				code.setCode(sender.getCode());
				code.setCodeType(CodeType.Send);
				Gson gson = new Gson();  
				
		        String strParams = gson.toJson(params);
		        code.setParams(strParams);
				code.setImei(imei);
				
				String serverIp = NetUtils.getLocalIP();
				code.setServerIp(serverIp);
				code.setDeviceType(Constant.DEVICETYPE);
				String sessionId = (String) TransactionContext.getData(Constant.SESSIONID);
				code.setSessionId(sessionId);
				
				dao.insert(code);
				
				
				
			}catch(Exception e) {
				loger.error(e);
			}
			
		}
	
	}

}
